from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate,login
from django.contrib.auth.models import User
from django.views.generic import View
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.core.mail import send_mail
from django.conf import settings
from itsdangerous import SignatureExpired
from celery_tasks.tasks import send_active_email
import re

# Create your views here.

# 定义RegisterView视图类,在这个类中定义注册所需的get方法以及post方法，
# 这个方法名必须等同于请求方式名

# 首页
def index(request):
    return render(request,'index.html')

#注册视图
class RegisterView(View):
    '''注册'''
    def get(self, request):
        # 显示注册页面
        return render(request,'register.html')
    # 处理用户数据
    def post(self,request):
        # 处理用户数据
        usrname = request.POST.get("user_name")
        password = request.POST.get("pwd")
        email = request.POST.get('email')
        allow = request.POST.get('allow')

        # 2 判断用户传递过来的数据是否存在，不存在返回错误信息提示
        if not all([usrname, password, email, allow]):
            return render(request, "register.html", {"error_msg": "数据不完整"})
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, "register.html", {"error_msg": "邮箱格式不正确"})
        if allow != "on":
            return render(request, "register.html", {"error_msg": "请勾选同意"})

        # 用户进行注册
        try:
            #校验用户是否存在
            user = User.objects.get(username=usrname)
        except User.DoesNotExist:
            """如果出现该异常说明用户名不存在，则让user对象为空"""
            user = None

        # 如果user对象存在，则表示用户名已存在，返回错误提示信息
        if user:
            return redirect(reverse('goods:index'), {"error_msg": "用户名已存在"})
        user = User.objects.create_user(username=usrname, email=email, password=password)
        user.is_active = 0
        user.save()

        serializer = Serializer(settings.SECRET_KEY, 3600)
        info = {"confirm":user.id}
        token = serializer.dumps(info).decode()

        # 发送邮件 激活链接
        # 邮件标题
        subjiect = '海马升仙欢迎你'
        # 发件人
        sender = settings.EMAIL_FROM
        # 邮件正文
        message = '欢迎你'
        # 收件人
        receiver = [email]
        html_message = """
        <h1>%s 恭喜您成为海马生鲜注册会员</h1><br/>
        <h3>请您在1小时内点击以下链接进行账户激 活</h3>
        <a href="http://127.0.0.1:8000/active/%s">
        http://127.0.0.1:8000/active/%s</a> """ % (usrname, token, token)
        send_mail(subjiect, message, sender, receiver,html_message=html_message)

        # 发邮件
        #send_active_email.delay(email, usrname, token)

        return redirect(reverse("goods:index"))
# 定义义ActiveView类，在这个类中定义get方法，用于处理用户激活
class ActiveView(View):
    '''
    账户激活
    '''
    def get(self,request, token):
        """ 用户激活"""
        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            # 解密
            info = serializer.loads(token)
            # 获取用户id
            user_id = info['confirm']
            # 根据该用户的id 获取用户对想
            user = User.objects.get(id = user_id)
            # 设置该用户对象中的is_active字段的值为1
            user.is_active =1
            user.save()
            # 使用反向解析跳转到登录页面
            return redirect(reverse("goods:login"))
        except SignatureExpired as e:
            return HttpResponse("激活链接已失效")
# 创建LoginView类并在这个类中定义get方法用于显示登录页
class LoginView(View):
    """登录"""
    def get(self,request):
        """显示登录页面"""
        # 判断是否记住用户名
        if 'username' in request.COOKIES:
            username = request.COOKIES.get('username')
            checked = "checked"
        else:
            username =""
            checked =""
        return render(request,'login.html',{"username":username, "checked":checked})
    def post(self, request):
        """登录校验"""
        # 接收数据
        username = request.POST.get("username")
        password = request.POST.get("pwd")

        # 校验参数完整性
        if not all([username,password]):
            return render(request,'login.html',{"error_msg":"数据不完整"})
        # 业务处理，登录校验
        user = authenticate(username=username, password=password)
        if user is not None:
            # 用户名正确
            if user.is_active:
                # 用户已激活，记录用户登录状态
                login(request, user)
                response = redirect(reverse("goods:index"))
                # 判断是否需要记住用户名
                remember = request.POST.get("remember")
                if remember == "on":
                    # 记住用户名
                    response.set_cookie("username",username,max_age=7*24*3600)
                else:
                    response.delete_cookie("username")
                # 跳转到首页
                return response
            else:
                # 用户未激活
                return render(request, "login.html", {"error_msg":"账户未激活"})
        else:
            # 用户名或密码错误
            return render(request, "login.html", {"error_msg":"用户名或密码错误"})
# 404 报错页面
def not_find_page(request):
    return render(request,'404.html')







def register(request):
    '''注册'''
    #当请求为get时表示请求注册页面，否则，处理用户注册数据
    if request.method == "GET":
        '''显示注册页面'''
        return render(request,'register.html')
    else:
        '''处理用户数据'''
        usrname = request.POST.get("user_name")
        password = request.POST.get("pwd")
        email = request.POST.get('email')
        allow = request.POST.get('allow')
        # 2 判断用户传递过来的数据是否存在，不存在返回错误信息提示
        if not all([usrname, password, email, allow]):
            return render(request, "register.html", {"error_msg": "数据不完整"})
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, "register.html", {"error_msg": "邮箱格式不正确"})
        if allow != "on":
            return render(request, "register.html", {"error_msg": "请勾选同意"})
        # 用户进行注册
        try:
            user = User.objects.get(username=usrname)
        except User.DoesNotExist:
            """如果出现该异常说明用户名不存在，则让user对象为空"""
            user = None
        # 如果user对象存在，则表示用户名已存在，返回错误提示信息
        if user:
            return redirect(reverse('goods:index'), {"error_msg": "用户名已存在"})
        user = User.objects.create_user(username=usrname, email=email, password=password)
        user.is_active = 0
        user.save()

        # 发送激活邮件，包含激活链接
        # 激活链接包含 用户身份，加密信息

        # 加密用户身份信息 token
        serializer = Serializer(settings.SECRET_KEY,3600)
        info = {'confirm':user.id}
        token = serializer.dumps(info)

        # 返回应答，跳转首页
        return redirect(reverse("goods:index"))

def register_handle(request):
    '''
    处理用户数据
    :param request:
    :return:
    '''
    #  接收注册表单数据
    usrname = request.POST.get("user_name")
    password = request.POST.get("pwd")
    email = request.POST.get('email')
    allow = request.POST.get('allow')
    #2 判断用户传递过来的数据是否存在，不存在返回错误信息提示
    if not all([usrname, password, email, allow]):
        return render(request,"register.html",{"error_msg":"数据不完整"})
    if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9]+(\.[a-z]{2,5}){1,2}$',email):
        return render(request,"register.html",{"error_msg":"邮箱格式不正确"})
    if allow != "on":
        return render(request, "register.html" ,{"error_msg":"请勾选同意"})
    # 用户进行注册
    try:
        user = User.objects.get(username=usrname)
    except User.DoesNotExist:
        """如果出现该异常说明用户名不存在，则让user对象为空"""
        user = None
    # 如果user对象存在，则表示用户名已存在，返回错误提示信息
    if user:
        return  redirect(reverse('goods:index'),{"error_msg":"用户名已存在"})
    user = User.objects.create_user(username=usrname, email=email, password=password)
    user.is_active =0
    user.save()
    return redirect(reverse("goods:index"))








